package com.three.iot.rest.controller.api;

/**
 * @author luiz
 * @Title: LoginController
 * @ProjectName iot
 * @Description: TODO
 * @date 2019-04-04 15:49
 */

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.three.iot.api.DataStoreService;
import com.three.iot.api.LoginInfoService;
import com.three.iot.commons.dto.UserModiPassDto;
import com.three.iot.commons.enums.Result;
import com.three.iot.commons.enums.ResultCode;
import com.three.iot.commons.po.UserInfo;
import com.three.iot.commons.utils.IDUtils;
import com.three.iot.rest.constants.SsoConstant;
import com.three.iot.rest.utils.RequestUtils;
import com.three.iot.rest.utils.ValidatorUtil;
import com.three.iot.rest.vo.LoginVo;
import com.three.iot.rest.vo.api.UserModiVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * <p>
 * 用户登录 前端控制器
 * </p>
 *
 * @author luiz
 * @since 2019-04-03
 */
@Controller
@RequestMapping("/api")
@Api(tags = "登录相关", description = "登录相关API")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    LoginInfoService loginInfoService;
    @Resource
    DataStoreService dataStoreService;
    @Resource
    DefaultKaptcha defaultKaptcha;
    /**
     * 是否显示验证码
     */
    @Value("${user.login.verify:N}")
    private String showVerify;

     @GetMapping("/showKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            String randomStr = httpServletRequest.getParameter("d");
            //生产验证码字符串并保存到session中
            String kaptchaCode = defaultKaptcha.createText();
            //session会话在分布式环境不能保持，临时存到redis
            dataStoreService.put(randomStr, kaptchaCode);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(kaptchaCode);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
            logger.info("sessionId:{},vrifyCode:{}", randomStr, kaptchaCode);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    /**
     * Login
     *
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String loginNo = loginVo.getLoginNo();
        if (StringUtils.isBlank(loginNo)) {
            return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(), "登录号不能为空");
        }
        String loginPass = loginVo.getLoginPass();
        if (StringUtils.isBlank(loginPass)) {
            return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(), "密码不能为空");
        }
        try {
            Result result = loginInfoService.doLogin(loginNo, loginPass);
            if (!result.isSuccess()) {
                return result;
            }
            UserInfo userInfo = (UserInfo) result.getData();
            String tokenId = IDUtils.genIdStr("T");
            dataStoreService.put(tokenId, JSONObject.toJSONString(userInfo));
            return Result.newSuccess(tokenId);
        } catch (Exception e) {
            logger.error("登录发生异常:{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    /**
     * Logout
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ResponseBody
    public Result<String> logout(HttpServletRequest request) {
        String tokenId = request.getHeader(SsoConstant.SSO_TOKENID);
        if (StringUtils.isBlank(tokenId)) {
            return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(), "tokenId 不能为空.");
        }
        // logout
        dataStoreService.del(tokenId);
        return Result.newSuccess();
    }

    /**
     * getCurrentUser
     *
     * @param request
     * @return
     */
    @GetMapping("/getCurrentUser")
    @ResponseBody
    public Result<UserInfo> getCurrentUser(HttpServletRequest request) {
        UserInfo userInfo = RequestUtils.getCurrentUser(request);
        //logger.info("获取当前用户信息:{}",userInfo);
        if (userInfo == null) {
            return Result.newError(ResultCode.USER_NO_LOGGED_IN.getCode(), "当前账户未登录");
        }
        return Result.newSuccess(userInfo);
    }

    @ResponseBody
    @RequestMapping(value = "modiPass", method = RequestMethod.POST)
    @ApiParam(name = "userModiVo", value = "用户修改实体 userModiVo", required = true)
    public Result<String> modiPass(@RequestBody UserModiVo userModiVo) {
        try {
            //校验用户实体字段，
            ValidatorUtil.validateEntity(userModiVo);
            UserModiPassDto userModiPassDto = new UserModiPassDto();
            BeanUtils.copyProperties(userModiVo, userModiPassDto);
            return loginInfoService.doModiPass(userModiPassDto);
        } catch (Exception e) {
            logger.error("修改密码修改异常!{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

}